import { Component, Input, ElementRef, AfterViewInit, ViewChild } from '@angular/core';
import { FormulaService } from "../../services/formular.service";
import * as katex from 'katex';
import 'katex/dist/katex.min.css';

@Component({
  selector: 'app-formula',
  template: '<span #formulaContainer></span>'
})
export class FormulaComponent implements AfterViewInit {
  @Input() formulaId!: string;
  @Input() formulaString!: string;
  @Input() displayMode = false;

  @ViewChild('formulaContainer', { static: true }) formulaContainer!: ElementRef<HTMLElement>;

  ngAfterViewInit() {
    this.chooseMethod();
  }

  private chooseMethod() {
    let formula: string | null = null;

    if (this.formulaId) {
      formula = FormulaService.getFormula(this.formulaId);
      if (!formula) {
        this.formulaContainer.nativeElement.textContent = '[公式未找到]';
        return;
      }
    } else if (this.formulaString) {
      formula = this.formulaString;
    }

    if (formula) {
      this.renderFormula(formula);
    } else {
      this.formulaContainer.nativeElement.textContent = '[无公式内容]';
    }
  }

  private renderFormula(latex: string) {
    try {
      katex.render(latex, this.formulaContainer.nativeElement, {
        displayMode: this.displayMode,
        throwOnError: false,
        strict: false
      });
    } catch (err) {
      console.error('KaTeX 渲染失败:', err);
      this.formulaContainer.nativeElement.textContent = '[渲染错误]';
    }
  }
}
